package com.study.base.io.nio.filechannel;

import javassist.expr.NewExpr;
import sun.nio.ch.DirectBuffer;

import java.io.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelTest {
	public static void main(String[] args) throws IOException {
		String filePath = "C:\\Users\\Administrator\\Downloads\\d8c9560bbac024d83aa1b1cb8aabbbf9.mp4";
		mappedByteBufferTest(filePath);

		//randomAccessFileTest(filePath);
	}

	public static void bufferedInputStreamTest(String filePath) throws IOException {

	}

	public static void randomAccessFileTest(String filePath) throws IOException {
		RandomAccessFile file = new RandomAccessFile(filePath, "r");
		byte[] bytes = new byte[(int) file.length()];
		long startTime = System.currentTimeMillis();
		file.read(bytes);
		long endTime = System.currentTimeMillis();
		System.out.println("r time :"+(endTime - startTime));
		file.close();
	}


	public static void  mappedByteBufferTest(String filePath) throws IOException {
		File file  = new File(filePath);
		FileInputStream inputStream = new FileInputStream(file);
		FileChannel fileChannel = inputStream.getChannel();
		MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());

		byte[] bytes = new byte[(int) file.length()];

		long startTime = System.currentTimeMillis();
		mappedByteBuffer.get(bytes);
		long endTime  =  System.currentTimeMillis();

		System.out.println("r time :"+(endTime - startTime));

		startTime = System.currentTimeMillis();
		mappedByteBuffer.load();
		endTime  =  System.currentTimeMillis();
		System.out.println("r time :"+(endTime - startTime));

		//写入到内存缓冲区
		mappedByteBuffer.put("ggg".getBytes());
		//强制保存到文件
		mappedByteBuffer.force();

		inputStream.close();
	}
}
